import { EventEmitter } from 'events';

// 自定义类型
type Callback = (...args: any[]) => void;
type EventHandler = (...args: any[]) => void;

// 使用BroadcastChannel API进行跨窗口通信
let broadcastChannel: BroadcastChannel | null = null;

try {
  broadcastChannel = new BroadcastChannel('nextcollab-socket-events');
  console.log('[Socket Mock] 创建BroadcastChannel成功');
} catch (error) {
  console.error('[Socket Mock] BroadcastChannel不可用:', error);
  // 某些旧浏览器不支持BroadcastChannel
}

// Socket模拟类
class MockSocket {
  private events: Map<string, EventHandler[]>;
  private connected: boolean;
  private id: string;
  // 将emitter改为public，以便广播频道可以访问
  public emitter: EventEmitter;

  constructor() {
    this.events = new Map();
    this.connected = true;
    this.id = `socket-${Math.random().toString(36).substring(2, 9)}`;
    this.emitter = new EventEmitter();
    this.emitter.setMaxListeners(50); // 允许更多监听器
  }

  // 监听事件
  on(event: string, handler: EventHandler): void {
    this.emitter.on(event, handler);
    
    // 存储事件处理器以便管理
    if (!this.events.has(event)) {
      this.events.set(event, []);
    }
    this.events.get(event)?.push(handler);
    
    console.log(`[Socket Mock] 添加事件监听: ${event}`);
  }

  // 触发一次事件
  once(event: string, handler: EventHandler): void {
    this.emitter.once(event, handler);
    console.log(`[Socket Mock] 添加一次性事件监听: ${event}`);
  }

  // 发送事件
  emit(event: string, ...args: any[]): void {
    console.log(`[Socket Mock] 发送事件: ${event}`, args);
    
    // 对特定事件进行处理
    if (event === 'content-update') {
      // 1. 发送到当前页面
      setTimeout(() => {
        this.emitter.emit(event, ...args);
      }, 10);
      
      // 2. 通过BroadcastChannel广播到其他窗口
      if (broadcastChannel) {
        try {
          broadcastChannel.postMessage({
            event,
            args,
            sourceId: this.id, // 标识消息来源
            timestamp: Date.now()
          });
        } catch (error) {
          console.error('[Socket Mock] 广播消息失败:', error);
        }
      }
    } else {
      // 其他事件只在当前页面处理
      this.emitter.emit(event, ...args);
    }
  }

  // 断开连接
  disconnect(): void {
    this.connected = false;
    console.log(`[Socket Mock] 断开连接`);
    this.emitter.emit('disconnect');
  }

  // 移除事件监听器
  off(event: string, handler?: EventHandler): void {
    if (handler) {
      this.emitter.off(event, handler);
    } else {
      this.emitter.removeAllListeners(event);
    }
    console.log(`[Socket Mock] 移除事件监听: ${event}`);
  }

  // 判断是否已连接
  get isConnected(): boolean {
    return this.connected;
  }

  // 获取socket ID
  get socketId(): string {
    return this.id;
  }
}

// 安全的事件处理函数
export function safeEventHandler<T>(handler: (data: T) => void): (data: T) => void {
  return (data: T) => {
    try {
      handler(data);
    } catch (error) {
      console.error('[Socket] 事件处理器错误:', error);
    }
  };
}

// 创建Socket实例
let socketInstance: MockSocket | null = null;

// 监听来自其他窗口的广播消息
if (broadcastChannel) {
  broadcastChannel.onmessage = (event) => {
    const { event: eventName, args, sourceId, timestamp } = event.data;
    
    console.log(`[Socket Mock] 收到广播消息: ${eventName}`, {
      sourceId,
      timestamp,
      currentSocketId: socketInstance?.socketId
    });
    
    // 确保socketInstance已创建
    if (socketInstance && sourceId !== socketInstance.socketId) {
      console.log(`[Socket Mock] 转发广播消息到本地: ${eventName}`);
      // 将消息转发到本地事件发射器
      socketInstance.emitter.emit(eventName, ...args);
    }
  };
}

export function createSocketConnection(): MockSocket {
  if (!socketInstance) {
    socketInstance = new MockSocket();
    console.log('[Socket Mock] 创建新的Socket连接');
  }
  return socketInstance;
}

export function getSocket(): MockSocket | null {
  return socketInstance;
}

export default MockSocket; 